package com.xuetang9.fujian.threaddemo;

import javax.swing.*;
import java.awt.*;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/2 10:31
 * @version: V1.0
 * @package: com.xuetang9.fujian.threaddemo
 **/
public class ProcessBarDemo extends JFrame {
    // 进度条控件
    private JProgressBar progressBar = new JProgressBar();

    // 开始按钮
    private JButton btnStart = new JButton("开启线程");
    private JButton btnPause = new JButton("暂停线程");

    // 更新进度条的任务
    private ProgressTask progressTask = null;

    public ProcessBarDemo(){
        setTitle("使用多线程控制进度条");
        JPanel topPane = new JPanel();
        topPane.add(btnStart);
        topPane.add(btnPause);
        getContentPane().add(topPane, BorderLayout.SOUTH);
        progressBar.setStringPainted(true);
        getContentPane().add(progressBar, BorderLayout.CENTER);
        // 给按钮添加事件
        btnStart.addActionListener(e -> {
            this.progressTask = new ProgressTask(this.progressBar);
            Thread thread = new Thread(this.progressTask);
            new Thread(new LanterTask(ProcessBarDemo.this)).start();
            thread.start();
        });
        btnPause.addActionListener(e -> {
            if (null != this.progressTask){
                progressTask.stop();
            }
        });
        setSize(500, 400);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ProcessBarDemo();
            }
        });
    }

}
